package com.central.scheduler.plugin.task.datasource;

import com.central.common.enums.DbType;
import com.central.common.model.DatasourceInfo;
import com.central.scheduler.plugin.task.datasource.hive.HiveDatasourceProcessor;
import com.central.scheduler.plugin.task.datasource.mysql.MysqlDatasourceProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

/**
 * @author Tindy
 * @date 2021/12/23
 * @describe
 */
public class DatasourceUtil {

    private DatasourceUtil() {
    }

    private static final Logger logger = LoggerFactory.getLogger(DatasourceUtil.class);

    private static final DatasourceProcessor mysqlProcessor = new MysqlDatasourceProcessor();
    private static final DatasourceProcessor hiveProcessor = new HiveDatasourceProcessor();

    public static ConnectionParam buildConnectionParams(DbType dbType, DatasourceInfo datasource) {
        return getDatasourceProcessor(dbType).createConnectionParams(datasource);
    }

    public static Connection getConnection(DbType dbType, ConnectionParam connectionParam) {
        try {
            return getDatasourceProcessor(dbType).getConnection(connectionParam);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getJdbcUrl(DbType dbType, ConnectionParam baseConnectionParam) {
        return getDatasourceProcessor(dbType).getJdbcUrl(baseConnectionParam);
    }

    public static DatasourceProcessor getDatasourceProcessor(DbType dbType) {
        switch (dbType) {
            case MYSQL:
                return mysqlProcessor;
            case HIVE:
                return hiveProcessor;
            default:
                throw new IllegalArgumentException("datasource type illegal:" + dbType);
        }
    }

}
